<div class="form_item">
  <% external_fetch_task = (scope[:task].getAppropriateTask().getArtifactOrigin() == 'external') %>
  <textarea id="gocd-fetch-artifact_template" class="template">
    <%= render :partial => 'admin/tasks/fetch/gocd_artifact_config', :locals => {:scope => {:var_form => scope[:form]}} %>
  </textarea>

  <textarea id="external-fetch-artifact_template" class="template">
    <%= render :partial => 'admin/tasks/fetch/external_artifact_config', :locals => {:scope => {:var_form => scope[:form], :task => scope[:task], :artifact_plugin_to_fetch_view => scope[:artifact_plugin_to_fetch_view]}} %>
  </textarea>

  <div class="form_item_block">
    <%= scope[:form].radio_button "selectedTaskType", "gocd", :id => "task_artifact_type_gocd", :title => 'GoCD', :checked => !external_fetch_task, :class => 'fetch_artifact_type' -%>
    <%= scope[:form].label 'artifact_type_gocd', 'GoCD' %>
    <%= scope[:form].radio_button "selectedTaskType", "external", :id => "task_artifact_type_external", :title => 'External', :checked => external_fetch_task, :class => 'fetch_artifact_type' -%>
    <%= scope[:form].label 'artifact_type_external', 'External' %>
  </div>

  <div class="form_item_block">
    <%= label_tag random_dom_id('pipeline_'), 'Pipeline' -%>
    <%= scope[:form].text_field com.thoughtworks.go.config.FetchTask::PIPELINE_NAME %>
    <div class="contextual_help has_go_tip_right" title="The name of direct upstream pipeline or ancestor pipeline of one of the upstream pipelines on which the pipeline of the job depends on. The pipeline should be a dependency material or should be reachable as an ancestor(of the form fetch-from-pipeline/path/to/upstream-pipeline) of at-least one dependency material. Defaults to current pipeline if not specified."></div>
    <%= error_message_on(@task, com.thoughtworks.go.config.FetchTask::PIPELINE_NAME, :css_class => "form_error") %>
  </div>
  <div class="form_item_block">
    <%= label_tag random_dom_id('pipeline_'), required_label_text('Stage') -%>
    <%= scope[:form].text_field com.thoughtworks.go.config.FetchTask::STAGE %>
    <div class="contextual_help has_go_tip_right" title="The name of the stage to fetch artifacts from."></div>
    <%= error_message_on(@task, com.thoughtworks.go.config.FetchTask::STAGE, :css_class => "form_error") %>
  </div>
  <div class="form_item_block">
    <%= label_tag random_dom_id('pipeline_'), required_label_text('Job') -%>
    <%= scope[:form].text_field com.thoughtworks.go.config.FetchTask::JOB %>
    <div class="contextual_help has_go_tip_right" title="The name of the job to fetch artifacts from."></div>
    <%= error_message_on(@task, com.thoughtworks.go.config.FetchTask::JOB, :css_class => "form_error") %>
  </div>
  <% if external_fetch_task %>
    <div class="fetch-artifact-config">
      <%= render :partial => 'admin/tasks/fetch/external_artifact_config', :locals => {:scope => {
        :var_form => scope[:form], :task => scope[:task], :artifact_plugin_to_fetch_view => scope[:artifact_plugin_to_fetch_view]}} %>
    </div>
  <% else %>
    <div class="fetch-artifact-config">
      <%= render :partial => 'admin/tasks/fetch/gocd_artifact_config', :locals => {:scope => {:var_form => scope[:form], :task => scope[:task]}} %>
    </div>
  <% end %>
</div>

<script type="text/javascript">
  var pipelineJson         = <%== scope[:pipeline_json] %>;
  var pluginToFetchView    = <%== com.google.gson.Gson.new.toJson(scope[:artifact_plugin_to_fetch_view]) %>;
  var currentPipelineName  = '<%= @pipeline.name() %>';
  var isFormEdited         = false;

  Util.on_load(function () {
    var pipelines       = <%== @pipeline_json %>;
    var fetchTaskEditor = new TaskEditor.FetchTaskEditor();
    fetchTaskEditor.wireInAutocomplete(jQuery("#task_pipelineName"), jQuery("#task_stage"), jQuery("#task_job"), pipelines, currentPipelineName);
    jQuery('#task_form input[type="radio"]').on('change', showFetchTaskView);
    jQuery('#task_pipelineName, #task_stage, #task_job').on('input propertychange paste result', function () {
      showFetchTaskView(true);
    });


    showFetchTaskView(false);
  });

  function showFetchTaskView(isEdited) {
    isFormEdited = isEdited;
    getSelectedTaskType() === "external" ? renderExternalFetchTaskView() : renderGoCDFetchTaskView();
  }

  function renderGoCDFetchTaskView() {
    jQuery(".fetch-artifact-config").html(getTemplate("gocd-fetch-artifact_template"));
  }

  function renderExternalFetchTaskView() {
    jQuery(".fetch-artifact-config").html(getTemplate("external-fetch-artifact_template"));
    clearArtifactId();

    if (isAnyParameterized('task_pipelineName', 'task_stage', 'task_job')) {
      showPluginSelectionDropdown();
    } else {
      jQuery(".plugin_key_value").remove();
      hidePluginSelectionDropdown();
      initArtifactIdAutoComplete();
      renderViewForSelectedArtifactId();
      jQuery("#task_artifactId").on("input propertychange paste result", function () {
        isFormEdited = true;
        renderViewForSelectedArtifactId();
      })
    }
  }

  function clearArtifactId() {
    if (isFormEdited) {
      jQuery("#task_artifactId").val("");
    }
  }

  function renderViewForSelectedArtifactId() {
    var artifactId = jQuery("#task_artifactId").val();
    if (!artifactId || artifactId.trim().length === 0) {
      hidePluginSelectionDropdown();
      return;
    }

    var parameterized = isParameterized(artifactId);
    if (parameterized && isFormEdited) {
      showPluginSelectionDropdown();
      return;
    }

    if (parameterized && !isFormEdited) {
      jQuery(".plugin_key_value").show();
      return;
    }

    renderPluginView(determinePluginId(artifactId));
  }

  function resetPluginDropdown() {
    jQuery("#task_pluginId").prop("selectedIndex", 0);
  }

  function renderPluginView(pluginId) {
    if (pluginId) {
      hidePluginSelectionDropdown();
      jQuery("#task_pluginId").val(pluginId);
      jQuery(".plugin_key_value").hide();
      jQuery("#fetch_pluggable_task_view").show();
      jQuery("#fetch_pluggable_task_view").html(getFetchArtifactView(pluginId));
      initializeAngular();
    } else {
      jQuery(".plugin_key_value").show();
      showPluginSelectionDropdown();
      resetPluginDropdown();
      jQuery("#fetch_pluggable_task_view").html("");
      jQuery("#fetch_pluggable_task_view").hide();
    }
  }

  function getFetchArtifactView(pluginId) {
    for (var i in pluginToFetchView) {
      if (pluginId === pluginToFetchView[i].id) {
        var view =  pluginToFetchView[i].view;
        return isBlank(view) ? "<div class='form_error'>Plugin view not available: Looks like plugin[\" + pluginId + \"] does not support fetch artifact configuration!</div>" : view;
      }
    }

    return "<div class='form_error'>Plugin view not available: Looks like plugin["+pluginId+"] is missing!</div>";
  }

  function isBlank(str){
    return str === null || str === undefined || str.trim().length === 0;
  }

  function showPluginSelectionDropdown() {
    jQuery(".artifact_plugin_selection").show();
    jQuery("#task_pluginId").change(function () {
      renderPluginView(jQuery(this).val());
    });
  }

  function hidePluginSelectionDropdown() {
    jQuery(".artifact_plugin_selection").hide();
  }

  function initArtifactIdAutoComplete() {
    jQuery("#task_artifactId").autocomplete(getAllArtifactIdsInJob(pipeline(), stage(), job()), {
      multiple:      false,
      minChars:      0,
      matchContains: true,
      selectFirst:   false,
      width:         248
    });
  }

  function determinePluginId(artifactId) {
    var artifactInJob = getAllArtifactsFor(pipeline(), stage(), job());
    return artifactInJob ? artifactInJob[artifactId] : null;
  }

  function getAllArtifactIdsInJob(pipelineName, stageName, jobName) {
    var artifactInJob       = getAllArtifactsFor(pipelineName, stageName, jobName);
    var allArtifactIdsInJob = [];
    for (var artifactId in artifactInJob) {
      allArtifactIdsInJob.push(artifactId);
    }
    return allArtifactIdsInJob;
  }

  function getAllArtifactsFor(pipelineName, stageName, jobName) {
    var newArtifactInPipeline = pipelineJson.find(function (pipelineMap) {
      return pipelineMap["pipeline"] == pipelineName;
    });
    if (!newArtifactInPipeline) {
      return null;
    }
    var newArtifactInStage = newArtifactInPipeline["stages"].find(function (stageMap) {
      return stageMap["stage"] == stageName;
    });
    if (!newArtifactInStage) {
      return null;
    }

    var newArtifactsInJob = newArtifactInStage["jobs"].find(function (jobMap) {
      return jobMap["job"] == jobName;
    });
    if (!newArtifactsInJob) {
          return null;
    }
    return newArtifactsInJob["artifacts"];
  }

  function isAnyParameterized() {
    if (arguments.length === 0) {
      return false;
    }
    for (var i in arguments) {
      var value = jQuery("#" + arguments[i]).val();
      if (isParameterized(value)) {
        return true;
      }
    }
    return false;
  }

  function isParameterized(value) {
    return value != null && value.indexOf("#{") !== -1
  }

  function getSelectedTaskType() {
    return jQuery('input[name="task[selectedTaskType]"]:checked', '#task_form').val();
  }

  function getTemplate(template_id) {
    var template = jQuery("#" + template_id).val();
    return template ? template : "";
  }

  function pipeline() {
    var selectedPipelineNameWithAncestor = jQuery("#task_pipelineName").val();
    return selectedPipelineNameWithAncestor || currentPipelineName;
  }

  function stage() {
    return jQuery("#task_stage").val();
  }

  function job() {
    return jQuery("#task_job").val();
  }

  function initializeAngular() {
    new TaskPluginView().initialize("fetch_pluggable_task_view", "fetch_external_artifact_data", "task[<%==com.thoughtworks.go.config.FetchPluggableArtifactTask::CONFIGURATION%>]");
    new TaskPluginView().bootstrapAngular();
  }
</script>
